<?php
	namespace Common\Logic;
	use Common\Model\UserCouponModel;
	class UserCouponLogic extends UserCouponModel{
		/*
		* Function:		getUserCouponList
		* Description:	用户优惠券列表
		* @param:		$page string 起始页
						$filter array 过滤数组
						$pageSize string 每页显示条数
		*/
		public function getUserCouponList($page=1,$filter = '',$pageSize=20){
			$conditon = $this->getUserCouponFilter($filter);
			return $this->alias('a')->join('left join coupons b on a.tid=b.id')->field('a.*,b.image_url,b.title')->where($conditon)->order('a.id desc')->limit(($page-1)*$pageSize,$pageSize)->select();
		}
		
		/*
		* Function:get:	getUserCouponFilter
		* Description:	用户优惠券列表搜索过滤项
		* @param:		$filter array 过滤数组
		*/
		public function getUserCouponFilter($filter = ''){
			$conditon = array();
			$conditon['a.is_deleted'] = 0;
            $conditon['b.cate'] = 1;
			if(!empty($filter['user_id'])){
				$conditon['a.user_id'] = $filter['user_id'];
			}
			if(!empty($filter['order_id'])){
				$conditon['a.order_id'] = $filter['order_id'];
			}
			if($filter['status']!=''){
				$conditon['a.status'] = $filter['status'];
			}
			if(!empty($filter['condition_amount'])){
				$conditon['a.condition_amount'] = ['egt',$filter['condition_amount']];
			}
			if(!empty($filter['user_name'])){
				$wh = array();
				$wh['username'] = array('like','%'.$filter['user_name'].'%');
				$sql = D('User')->field('id')->where($wh)->select(false);
				$conditon['a.user_id'] = array('exp','in('.$sql.')');
			}
			if(!empty($filter['cate'])){
				$conditon['b.cate'] = $filter['cate'];
			}
			return $conditon;
		}
		
		/*
		* Function:get:	getUserCouponCount
		* Description:	用户优惠券列表总数
		* @param:		$filter array 过滤数组
		*/
		public function getUserCouponCount($filter = ''){
			$conditon = $this->getUserCouponFilter($filter);
			return $this->alias('a')->join('left join coupons b on a.tid=b.id')->where($conditon)->count();
		}
		
		/*
		* Function:		addUserCoupon
		* Description:	增加用户优惠券
		* @param:		$data array 增加的数组
		*/
		public function addUserCoupon($data){
			return $this->add($data);
		}
		
		/*
		* Function:		getUserCouponInfo
		* Description:	获取用户优惠券信息 by row
		* @param:		$id int ID
		*/
		public function getUserCouponInfo($id){
			return $this->where(array('id'=>$id))->find();
		}
		
		/*
		* Function:		updateUserCoupon
		* Description:	更新用户优惠券
		* @param:		$data array 更新的数组
		*/
		public function updateUserCoupon($data){
			return $this->save($data);
		}
		
		/*
		* Function:		deleteUserCoupon
		* Description:	删除用户优惠券
		* @param:		$id int ID
		*/
		public function deleteUserCoupon($id){
			return $this->where(array('id'=>$id))->delete();
		}
	}
?>